import React, { useState, useEffect, useRef } from 'react';
import { Modal, Form, Input, Select, Button, Space, Tag, Slider, DatePicker, Popover, message } from 'antd';
import { 
  CloseCircleOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { Task, TaskLevel, TaskType, TaskStatus, TaskSubType, getSubTypesByType, taskLevels, taskTypes } from '../models/taskModels';
import { updateTask, createTask } from '../../../services/taskService';
import { getStoredUserInfo } from '../../../utils/auth';
import { getUserNames } from '../../../services/user';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { Option } = Select;

export interface TaskEditModalProps {
  visible: boolean;
  task: Task;
  onCancel: () => void;
  onSuccess?: () => void;
  disableTitle?: boolean;
  requiredFields?: string[];
  forceStatus?: TaskStatus;
  hiddenFields?: string[];
  disableAllExcept?: string[];
}

/**
 * 任务编辑弹窗
 * 用于编辑任务详情
 */
const TaskEditModal: React.FC<TaskEditModalProps> = ({ 
  visible, 
  task, 
  onCancel,
  onSuccess,
  disableTitle = false,
  requiredFields = [],
  forceStatus,
  hiddenFields = [],
  disableAllExcept = []
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [selectedType, setSelectedType] = useState<TaskType>(task.type as TaskType);
  const [userOptions, setUserOptions] = useState<{ label: string; value: string }[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [processValue, setProcessValue] = useState<number>(task.process || 0);
  const [selectedText, setSelectedText] = useState<string>('');
  const [popoverVisible, setPopoverVisible] = useState<boolean>(false);
  const problemsTextAreaRef = useRef<any>(null);

  // 修改表单初始化部分，强制更新问题字段
  useEffect(() => {
    if (visible) {
      // 设置表单值的另一种方式，直接使用手动设置确保problems更新
      const values = {
        ...initialValues,
        problems: task.problems || ''
      };
      
      // 添加调试日志
      console.log('TaskEditModal初始化表单数据:', {
        task,
        problems: task.problems,
        initialValues: initialValues,
        finalValues: values
      });
      
      // 强制清空并重新设置，以确保数据正确绑定
      form.resetFields();
      
      // 使用setTimeout确保DOM更新后再设置字段值
      setTimeout(() => {
        form.setFieldsValue(values);
        
        // 额外确保problems字段被单独设置
        if(task.problems) {
          form.setFieldValue('problems', task.problems);
        }
      }, 0);
      
      setProcessValue(task.process || 0);
      fetchUserNames();
    }
  }, [visible, task, form]);

  // 获取用户名称列表
  const fetchUserNames = async () => {
    try {
      setLoadingUsers(true);
      const res = await getUserNames();
      if (res.code === 200 && res.data) {
        // 将后端返回的 "englishName/chineseName" 格式转换为下拉选项
        const options = res.data.map(item => {
          const [englishName, chineseName] = item.split('/');
          return {
            label: `${chineseName} (${englishName})`,
            value: item // 保存完整的 "englishName/chineseName" 字符串
          };
        });
        setUserOptions(options);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      setLoadingUsers(false);
    }
  };

  // 处理多选处理人
  const handleReceiversChange = (values: string[]) => {
    // 不需要在这里将列表转换为字符串，只保存列表值
    form.setFieldValue('receiver', values);
  };

  // 解析处理人字符串为数组
  const parseReceivers = (receiverStr?: string): string[] => {
    if (!receiverStr) return [];
    // 使用 | 分隔符分割处理人字符串
    return receiverStr.split('|');
  };
  
  // 表单初始值
  const initialValues = {
    title: task.title,
    type: requiredFields.includes('type') && task.type?.startsWith('暂无') ? '' : task.type,
    subType: requiredFields.includes('subType') && task.subType?.startsWith('暂无') ? '' : task.subType,
    level: requiredFields.includes('level') && task.level?.startsWith('暂无') ? '' : task.level,
    process: task.process,
    receiver: parseReceivers(task.receiver), // 将字符串解析为数组，以适应Select多选
    thisWeekPlan: task.thisWeekPlan || '',
    nextWeekPlan: task.nextWeekPlan || '',
    problems: task.problems || '', // 确保problems字段不为undefined
    creater: task.creater, // 添加创建人字段
    expectedDate: task.expectedDate ? dayjs(task.expectedDate) : undefined, // 期望完成时间
  };

  // 保存修改
  const handleSave = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      // 获取problems字段的当前值（直接从DOM元素获取作为备选）
      let problemsValue = values.problems;
      if (problemsTextAreaRef.current && (!problemsValue || problemsValue.trim() === '')) {
        problemsValue = problemsTextAreaRef.current.resizableTextArea.textArea.value || '';
      }
      
      // 添加调试日志，检查表单值和DOM值
      console.log('保存前的表单值:', {
        formValues: values,
        problemsField: values.problems,
        problemsDOM: problemsTextAreaRef.current?.resizableTextArea.textArea.value,
        finalProblems: problemsValue
      });
      
      // 将处理人数组转换为格式化的字符串
      const formattedReceiver = values.receiver && values.receiver.length > 0 
        ? values.receiver.join('|') 
        : undefined;
      
      // 获取当前用户信息
      const userInfo = getStoredUserInfo();
      const currentUser = userInfo?.englishName || '';
      
      // 处理日期格式
      let formattedExpectedDate = undefined;
      if (values.expectedDate) {
        formattedExpectedDate = values.expectedDate.format('YYYY-MM-DD');
      }
      
      // 如果任务状态为已完成，且没有设置完成时间，则自动设置为当前日期
      let finishedDate = task.finishedDate;
      if (task.status === 'done' || values.status === 'done') {
        finishedDate = dayjs().format('YYYY-MM-DD');
      }
      
      const taskData = {
        ...values,
        // 确保保留原始status，如果没有明确设置
        status: task.status,
        receiver: formattedReceiver, // 使用格式化后的处理人字符串
        updater: currentUser, // 添加修改人信息
        creater: task.creater, // 确保保留原始创建人
        expectedDate: formattedExpectedDate, // 期望完成时间
        finishedDate: finishedDate, // 实际完成时间
        problems: problemsValue || '', // 使用最终确定的问题值
        // 确保保留父任务ID
        parentId: task.parentId || undefined
      };
      
      // 如果有强制设置的状态，则覆盖状态值
      if (forceStatus) {
        taskData.status = forceStatus;
      }
      
      const response = await updateTask(task.id, taskData);
      
      if (response.code === 200) {
        if (onSuccess) {
          onSuccess();
        }
      }
    } catch (error) {
      console.error('保存任务失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理任务类型变更
  const handleTypeChange = (value: TaskType) => {
    setSelectedType(value);
    form.setFieldValue('subType', undefined);
  };

  // 判断字段是否禁用
  const isFieldDisabled = (fieldName: string): boolean => {
    // 如果disableAllExcept不为空，则只有在数组中的字段才能编辑
    if (disableAllExcept.length > 0) {
      return !disableAllExcept.includes(fieldName);
    }
    // 对于标题字段，使用disableTitle属性
    if (fieldName === 'title') {
      return disableTitle;
    }
    return false;
  };

  // 新增：处理文本选择
  const handleTextSelection = () => {
    // 检查是否是进行中的任务
    if (task.status !== 'inProgress') return;
    
    const selection = window.getSelection();
    if (!selection || selection.rangeCount === 0) return;
    
    const selectedText = selection.toString().trim();
    if (!selectedText) {
      setPopoverVisible(false);
      return;
    }
    
    // 设置选中的文本并显示提示框
    setSelectedText(selectedText);
    setPopoverVisible(true);
  };
  
  // 新增：创建新任务
  const handleCreateNewTask = async () => {
    if (!selectedText) return;
    
    try {
      setLoading(true);
      
      // 获取当前用户信息
      const userInfo = getStoredUserInfo();
      const currentUser = userInfo?.englishName || '';
      
      // 创建一个新任务
      const newTask: Partial<Task> = {
        title: selectedText.length > 50 ? selectedText.substring(0, 47) + '...' : selectedText,
        status: 'todo' as TaskStatus,
        creater: currentUser,
        type: '暂无分类' as TaskType,
        subType: '暂无子分类' as TaskSubType,
        level: '暂无' as TaskLevel,
        process: 0,
      };
      
      // 设置parent_id为当前任务的title_index，直接使用字符串类型
      if (task.titleIndex) {
        // 不再需要转换为数字类型
        newTask.parentId = task.titleIndex;
      }
      
      // 添加调试日志，确认parent_id设置正确
      console.log('创建子任务:', {
        parentTask: task,
        parentTitleIndex: task.titleIndex,
        parentIdForNewTask: newTask.parentId,
        newTask: newTask
      });
      
      const response = await createTask(newTask);
      
      if (response.code === 200) {
        setPopoverVisible(false);
        setSelectedText('');
        message.success('已成功创建新任务');
      } else {
        message.error('创建任务失败');
      }
    } catch (error) {
      console.error('创建任务失败:', error);
      message.error('创建任务失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 新增：关闭气泡框
  const handleClosePopover = () => {
    setPopoverVisible(false);
    setSelectedText('');
  };

  return (
    <Modal
      title={<div className="text-lg font-medium">编辑任务</div>}
      open={visible}
      onCancel={onCancel}
      width={700}
      footer={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" loading={loading} onClick={handleSave}>
            保存
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          ...initialValues,
          problems: task.problems || ''  // 确保problems字段在Form的initialValues中也正确设置
        }}
        key={`task-form-${task.id}-${visible}`}
      >
        <Form.Item
          name="title"
          label="任务标题"
          rules={[{ required: true, message: '请输入任务标题' }]}
        >
          <Input placeholder="请输入任务标题" disabled={isFieldDisabled('title')} />
        </Form.Item>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Form.Item
            name="type"
            label="需求类型"
            rules={[
              { required: requiredFields.includes('type'), message: '请选择需求类型' },
              { 
                validator: (_, value) => {
                  if (requiredFields.includes('type')) {
                    if (!value || value === '') {
                      return Promise.reject('需求类型不能为空');
                    }
                    if (value.startsWith('暂无')) {
                      return Promise.reject('需求类型不能选择暂无分类');
                    }
                  }
                  return Promise.resolve();
                } 
              }
            ]}
          >
            <Select placeholder="请选择需求类型" onChange={handleTypeChange} disabled={isFieldDisabled('type')}>
              {taskTypes.map(type => (
                <Option key={type} value={type}>{type}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="subType"
            label="子类型"
            rules={[
              { required: requiredFields.includes('subType'), message: '请选择子类型' },
              { 
                validator: (_, value) => {
                  if (requiredFields.includes('subType')) {
                    if (!value || value === '') {
                      return Promise.reject('子类型不能为空');
                    }
                    if (value.startsWith('暂无')) {
                      return Promise.reject('子类型不能选择暂无子分类');
                    }
                  }
                  return Promise.resolve();
                } 
              }
            ]}
          >
            <Select placeholder="请选择子类型" disabled={isFieldDisabled('subType')}>
              {getSubTypesByType(selectedType).map(subType => (
                <Option key={subType} value={subType}>{subType}</Option>
              ))}
            </Select>
          </Form.Item>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Form.Item
            name="level"
            label="复杂度"
            rules={[
              { required: requiredFields.includes('level'), message: '请选择复杂度' },
              { 
                validator: (_, value) => {
                  if (requiredFields.includes('level')) {
                    if (!value || value === '') {
                      return Promise.reject('复杂度不能为空');
                    }
                    if (value.startsWith('暂无')) {
                      return Promise.reject('复杂度不能选择暂无');
                    }
                  }
                  return Promise.resolve();
                } 
              }
            ]}
          >
            <Select placeholder="请选择复杂度" disabled={isFieldDisabled('level')}>
              {taskLevels.map(level => (
                <Option key={level} value={level}>{level}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="expectedDate"
            label="期望完成时间"
            tooltip="选择任务期望的完成日期"
          >
            <DatePicker 
              placeholder="请选择期望完成日期" 
              style={{ width: '100%' }}
              format="YYYY-MM-DD"
              disabled={isFieldDisabled('expectedDate')}
            />
          </Form.Item>
        </div>
        
        {/* 进度条单独一行 */}
        <Form.Item
          name="process"
          label="进度"
        >
          <div className="flex items-center">
            <div className="flex-grow mr-4">
              <Slider
                min={0}
                max={100}
                step={1}
                tipFormatter={value => `${value}%`}
                disabled={isFieldDisabled('process')}
                onChange={value => {
                  // 更新进度值状态和表单值
                  setProcessValue(value);
                  form.setFieldsValue({ process: value });
                }}
                value={processValue}
              />
            </div>
            <div className="w-16 flex items-center">
              <span className="text-base font-medium">{processValue}%</span>
            </div>
          </div>
        </Form.Item>
        
        <Form.Item
          name="receiver"
          label="处理人"
          tooltip="可选择多个处理人"
          rules={[{ required: requiredFields.includes('receiver'), message: '请选择处理人' }]}
        >
          <Select
            mode="multiple"
            placeholder="请选择处理人"
            loading={loadingUsers}
            showSearch
            options={userOptions}
            filterOption={(input, option) => 
              option?.label?.toString().toLowerCase().includes(input.toLowerCase()) || false
            }
            onChange={handleReceiversChange}
            disabled={isFieldDisabled('receiver')}
            tagRender={(props) => {
              const { label, value, closable, onClose } = props;
              // 自定义标签渲染，实现单独删除功能
              return (
                <Tag 
                  className="mr-1 mb-1" 
                  closable={!isFieldDisabled('receiver') && closable} 
                  onClose={onClose}
                  closeIcon={<CloseCircleOutlined className="ml-1" />}
                >
                  {label}
                </Tag>
              );
            }}
          />
        </Form.Item>
        
        {/* 本周工作字段 - 根据hiddenFields控制显示 */}
        {!hiddenFields.includes('thisWeekPlan') && (
          <Form.Item
            name="thisWeekPlan"
            label="本周工作"
          >
            <TextArea rows={3} placeholder="请输入本周工作" disabled={isFieldDisabled('thisWeekPlan')} />
          </Form.Item>
        )}
        
        {/* 下周计划字段 - 根据hiddenFields控制显示 */}
        {!hiddenFields.includes('nextWeekPlan') && (
          <Form.Item
            name="nextWeekPlan"
            label="下周计划"
          >
            <TextArea rows={3} placeholder="请输入下周计划" disabled={isFieldDisabled('nextWeekPlan')} />
          </Form.Item>
        )}
        
        {/* 存在的问题字段 - 根据hiddenFields控制显示 */}
        {!hiddenFields.includes('problems') && (
          <Form.Item
            name="problems"
            label="存在的问题"
            // 确保表单项正确渲染，即使initialValue可能为undefined
            initialValue={task.problems || ''}
          >
            <div className="relative">
              <TextArea 
                rows={3} 
                placeholder="请输入存在的问题" 
                disabled={isFieldDisabled('problems')} 
                onMouseUp={handleTextSelection} 
                onKeyUp={handleTextSelection}
                ref={problemsTextAreaRef}
                // 添加默认值作为备选方案
                defaultValue={task.problems || ''}
                // 添加key强制在task变化时重新渲染
                key={`problems-${task.id}-${visible}`}
                onFocus={() => {
                  // 检查文本域的值是否正确设置
                  const currentValue = form.getFieldValue('problems');
                  console.log('Problems field onFocus value:', currentValue);
                  
                  // 如果没有值但task中有problems，再次尝试设置
                  if(!currentValue && task.problems) {
                    form.setFieldValue('problems', task.problems);
                  }
                }}
              />
              {popoverVisible && task.status === 'inProgress' && (
                <div 
                  className="absolute bg-white shadow-md rounded p-3 border z-10"
                  style={{ 
                    top: '-60px', // 将提示框固定在problems输入框上方
                    left: '50%',
                    transform: 'translateX(-50%)',
                    whiteSpace: 'nowrap'
                  }}
                >
                  <div className="text-sm mb-2">是否新建为任务？</div>
                  <div className="flex justify-between">
                    <Button 
                      size="small" 
                      type="primary" 
                      onClick={handleCreateNewTask}
                      className="mr-2"
                      icon={<PlusOutlined />}
                    >
                      是
                    </Button>
                    <Button 
                      size="small" 
                      onClick={handleClosePopover}
                    >
                      否
                    </Button>
                  </div>
                  
                  {/* 三角形指示器，指向输入框 */}
                  <div 
                    className="absolute"
                    style={{
                      width: '10px',
                      height: '10px',
                      transform: 'rotate(45deg)',
                      backgroundColor: 'white',
                      borderRight: '1px solid #e8e8e8',
                      borderBottom: '1px solid #e8e8e8',
                      bottom: '-5px',
                      left: '50%',
                      marginLeft: '-5px',
                      zIndex: 1
                    }}
                  ></div>
                </div>
              )}
            </div>
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};

export default TaskEditModal; 